package com.samphanie.security.utils;

import com.samphanie.security.validation.ValidateCodeProcessorHolder;
import com.samphanie.security.validation.enums.ValidateCodeType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ZSY
 * @email 1451691457@qq.com
 */
@Slf4j
@Component
public class SmsCodeUtil {

    private static ValidateCodeProcessorHolder validateCodeProcessorHolder;

    public static void checkSmsCode(String code, HttpServletRequest request, HttpServletResponse response) {
        if (!request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            ValidateCodeType type = ValidateCodeType.SMS;
            log.debug("校验请求(" + request.getRequestURI() + ")中的验证码,验证码类型" + type);
            validateCodeProcessorHolder.findValidateCodeProcessor(type)
                    .validate(new ServletWebRequest(request, response), code);
            log.debug("验证码校验通过");
        }
    }

    @Autowired
    public void setValidateCodeProcessorHolder(ValidateCodeProcessorHolder codeProcessorHolder) {
        validateCodeProcessorHolder = codeProcessorHolder;
    }

}
